package com.htd.erp.common;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;

import com.htd.erp.model.AbstractEntity;

/**
 * @author Zhang Guilin
 *
 */
@Named
@ConversationScoped
public class GenericRepository implements Repository, Serializable {
	private static final long serialVersionUID = -3570734825659963084L;
	
	@DataRepository
	@Inject
	private EntityManager entityManager;

	@Override
	public <T extends AbstractEntity> T create(T t) {
		entityManager.getTransaction().begin();
		entityManager.persist(t);
		entityManager.getTransaction().commit();
		return t;
	}

	@Override
	public <T extends AbstractEntity> T update(T t) {
		entityManager.getTransaction().begin();
		T attached = entityManager.merge(t);
		entityManager.getTransaction().commit();
		return attached;
	}

	@Override
	public <T extends AbstractEntity> T delete(Class<T> clazz, Long id) {
		T t = findById(clazz, id);
		t.setDeleted(true);
		return update(t);
	}

	@Override
	public <T extends AbstractEntity> T findById(Class<T> clazz, Long id) {
		T t = entityManager.find(clazz, id);
		if(t == null) {
			throw new EntityNotFoundException();
		}
		return t;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AbstractEntity> List<T> findAll(Class<T> clazz) {
		String query = new StringBuilder("FROM ").append(clazz.getSimpleName()).append(" WHERE deleted = false").toString();
		return entityManager.createQuery(query).getResultList();
	}
}
